import axios from 'axios';
import router from '../router';
import BASEURL from './helper'

let API_ADDRESS = BASEURL.BASEURL;


const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    // baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
    baseURL: process.env.NODE_ENV === 'development'? API_ADDRESS:API_ADDRESS,
    timeout: 5000*10
});

const _cloneDeep = require('lodash/cloneDeep')

// 移除空字符串，null, undefined
function clearEmptyParam(config) {
  ['data', 'params'].forEach(item => {
    if (config[item]) {
      const keys = Object.keys(config[item])
      if (keys.length) {
        keys.forEach(key => {
          const rawType = toRawType(config[item])
          if (['', undefined, null].includes(config[item][key]) &&
              ['Object'].includes(rawType)) {
            // 移除属性之前，进行深拷贝断开引用，避免影响页面
            config[item] = _cloneDeep(config[item])
            delete config[item][key]
          }
        })
      }
    }
  })
}

/**
 * @description 获取原始类型
 * @param {*} value
 * @returns {String} 类型字符串，如'String', 'Object', 'Null', 'Boolean', 'Number', 'Array'
 */
export function toRawType(value) {
  return Object.prototype.toString.call(value).slice(8, -1)
}


service.interceptors.request.use(
    config => {
        // if(!config.data.isToken || config.data.isToken==='undefined'){
        //     let token = JSON.parse(localStorage.getItem('adminToken')) || '';
        //     if(token){
        //         config.headers.token = token
        //     }else {
        //         Message.error('token为空');
        //         router.push({path:'/login'})
        //         return false
        //     }
        // }
        clearEmptyParam(config)
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
      return response.data
        // console.log(response)
        // if (response.data.code === 0) {
        //     return response.data.data;
        // } else {
        //   // return response.data
        //   Promise.reject();
        // }
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

export default service;
